Page({
  data: {
    work: {},          // 作品详情数据
    commentContent: '', // 评论输入内容
    isLikeLoading: false, // 点赞加载状态
    
    // 评论分页相关数据
    commentPageNum: 1, // 当前评论页码
    commentPageSize: 10, // 每页评论数量
    commentHasMore: true, // 是否还有更多评论
    commentIsLoading: false, // 是否正在加载评论
    commentIsRefreshing: false, // 是否正在刷新评论
    commentTotal: 0 // 评论总数量
  },

  onLoad(options) {
    // 获取从发现页传递的作品ID
    const workId = parseInt(options.id);
    const authorId = parseInt(options.authorId);
    // 获取作品详情数据
    this.getWorkDetail(workId,authorId);
  },

  onShow() {
    // 页面显示时获取用户点赞状态
    const { work } = this.data;
    if (work && work.id) {
      let userInfo = {};
      try {
        userInfo = wx.getStorageSync('userInfo');
      } catch (e) {
        console.error('获取用户信息失败', e);
      }

      if (userInfo.id) {
        let token = '';
        try {
          token = wx.getStorageSync('token');
        } catch (e) {
          console.error('获取token失败', e);
        }
        
        // 获取用户点赞状态
        this.getUserLikeStatus(work.id, token);
      }
    }
  },

  // 获取作品详情（根据workId查询）
  getWorkDetail(workId,authorId) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    // 从 Storage 中获取 token
    let token = '';
    try {
      token = wx.getStorageSync('token'); 
    } catch (e) {
      console.error('获取 token 失败', e);
    }

    // 先获取作品基本信息
    wx.request({
      url: `http://localhost:8080/works/works/listByAuthor?authorId=${authorId}`,
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (res.data.code === 200 && res.data.data) {
          // 从列表中找到匹配当前workId的作品
          const targetWork = res.data.data.find(item => item.workId === workId);
          
          if (targetWork) {
            // 处理多图，将逗号分隔的图片地址转为数组
            const images = targetWork.coverImg ? targetWork.coverImg.split(',') : [];
            // 格式化作品数据
            const formattedWork = {
              id: targetWork.workId,
              authorId: targetWork.authorId, // 添加authorId字段，用于点赞功能
              title: targetWork.title,
              avatar: targetWork.authorAvatar,
              username: targetWork.authorNickname,
              publishTime: this.formatTime(targetWork.workCreateTime),
              rawCreateTime: targetWork.workCreateTime,
              content: this.cleanHtmlTags(targetWork.content),
              images: images,
              likeCount: targetWork.likeCount,
              commentCount: targetWork.commentCount,
              viewCount: targetWork.viewCount,
              isLiked: false,
              comments: [] // 初始化评论数组
            };

            this.setData({ work: formattedWork });
            
            // 接着获取该作品的评论（第一页）
            this.getComments(workId, token, true);
            
            // 获取用户点赞状态
            this.getUserLikeStatus(workId, token);
          } else {
            wx.showToast({
              title: '未找到该作品',
              icon: 'none'
            });
            console.error('未找到ID为', workId, '的作品');
            wx.hideLoading();
          }
        } else {
          wx.hideLoading();
        }
      },
      fail: (err) => {
        console.error('作品数据加载失败', err);
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        });
        wx.hideLoading();
      }
    });
  },

  toUserDetail(options){
    const authorId = options.currentTarget.dataset.authorId;
    console.log('作者authorId:', authorId);
    wx.navigateTo({
      url: `/my/pages/user-detail/user-detail?userId=${authorId}`
    });
  },

  // 获取作品评论
  getComments(targetId, token, isRefresh = false) {
    if (this.data.commentIsLoading) {
      return;
    }

    // 如果是刷新，重置分页参数
    if (isRefresh) {
      this.setData({
        commentPageNum: 1,
        commentHasMore: true,
        commentIsRefreshing: true
      });
    }

    // 如果没有更多数据，直接返回
    if (!this.data.commentHasMore && !isRefresh) {
      return;
    }

    this.setData({
      commentIsLoading: true
    });

    // 构建请求参数
    const params = {
      targetId: targetId,
      pageNum: this.data.commentPageNum,
      pageSize: this.data.commentPageSize
    };

    wx.request({
      url: `http://localhost:8080/foodworks/comments/target`,
      method: 'GET',
      data: params,
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      success: (commentRes) => {
        if (commentRes.data.code === 200) {
          let newComments = [];
          
          // 处理分页数据
          if (commentRes.data.data && commentRes.data.data.list && Array.isArray(commentRes.data.data.list)) {
            // 后端返回分页数据格式
            newComments = commentRes.data.data.list;
            this.setData({
              commentTotal: commentRes.data.data.total || 0,
              commentHasMore: this.data.commentPageNum * this.data.commentPageSize < (commentRes.data.data.total || 0)
            });
          } else if (Array.isArray(commentRes.data.data)) {
            // 后端返回数组格式（兼容原有接口）
            newComments = commentRes.data.data;
            this.setData({
              commentHasMore: newComments.length === this.data.commentPageSize
            });
          }

          // 转换评论数据格式以匹配前端需求
          const formattedComments = newComments.map(comment => ({
            id: comment.id,
            authorId:comment.userId,
            avatar: comment.userAvatar || 'https://picsum.photos/100/100?random=default', // 默认头像
            username: comment.userNickname,
            time: this.formatTime(comment.createTime),
            content: this.cleanHtmlTags(comment.content),
            likeCount: comment.actualLikeCount || 0,
            isLiked: false, // 初始未点赞
            isLikeLoading: false // 初始加载状态
          }));

          // 更新作品数据，包含评论
          const { work } = this.data;
          
          if (isRefresh) {
            // 刷新时替换所有评论
            this.setData({
              work: {
                ...work,
                comments: formattedComments,
                commentCount: this.data.commentTotal || formattedComments.length
              }
            });
          } else {
            // 加载更多时追加评论
            this.setData({
              work: {
                ...work,
                comments: [...work.comments, ...formattedComments],
                commentCount: this.data.commentTotal || (work.comments.length + formattedComments.length)
              },
              commentPageNum: this.data.commentPageNum + 1
            });
          }

          // 获取评论点赞状态和点赞数
          if (formattedComments.length > 0) {
            const commentIds = formattedComments.map(comment => comment.id);
            
            // 获取用户点赞状态
            this.getCommentLikeStatus(commentIds, token);
            
            // 获取评论点赞数
            this.getCommentLikeCounts(commentIds, token);
          }
        } else {
          wx.showToast({
            title: commentRes.data.msg || '获取评论失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('获取评论失败', err);
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({
          commentIsLoading: false,
          commentIsRefreshing: false
        });
        wx.hideLoading();
      }
    });
  },

  // 获取用户点赞状态（统一使用与find页面相同的接口和逻辑）
  getUserLikeStatus(workId, token) {
    let userInfo = {};
    try {
      userInfo = wx.getStorageSync('userInfo');
    } catch (e) {
      console.error('获取用户信息失败', e);
      return;
    }

    if (!userInfo.id) {
      return;
    }

    wx.request({
      url: 'http://localhost:8080/likes/likes/getUserLikeStatus',
      method: 'POST',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        userId: userInfo.id,
        targetIds: [workId],
        targetType: 1
      },
      success: (res) => {
        console.log('获取点赞状态响应:', res.data);
        
        if (res.data.code === 200) {
          const likedIds = res.data.data || [];
          const isLiked = likedIds.includes(workId);
          
          this.setData({
            work: {
              ...this.data.work,
              isLiked: isLiked
            }
          });
        }
      },
      fail: (err) => {
        console.error('获取点赞状态失败:', err);
      }
    });
  },

  // 时间格式化工具函数
  formatTime(timeStr) {
    if (!timeStr) return '未知时间';
    
    const now = new Date();
    const createTime = new Date(timeStr);
    const diffMs = now - createTime;
    const diffMinutes = Math.floor(diffMs / (1000 * 60));
    const diffHours = Math.floor(diffMinutes / 60);
    const diffDays = Math.floor(diffHours / 24);

    if (diffMinutes < 60) {
      return `${diffMinutes}分钟前`;
    } else if (diffHours < 24) {
      return `${diffHours}小时前`;
    } else if (diffDays < 7) {
      return `${diffDays}天前`;
    } else {
      return `${createTime.getMonth() + 1}-${createTime.getDate()}`;
    }
  },
  // 处理点赞（统一使用与find页面相同的接口和逻辑）
  handleLike(e) {
    // 防止重复点击
    if (this.data.isLikeLoading) {
      return;
    }

    const { work } = this.data;
    // 从事件中获取workId，与find页面保持一致
    const workId = e.currentTarget.dataset.id;
    
    // 验证workId是否匹配
    if (workId && workId !== work.id) {
      console.error('workId不匹配');
      return;
    }
    
    // 获取用户信息
    let userInfo = null;
    try {
      userInfo = wx.getStorageSync('userInfo');
    } catch (e) {
      console.error('获取用户信息失败', e);
    }

    if (!userInfo || !userInfo.id) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 获取token
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    const isCurrentlyLiked = work.isLiked;
    
    // 乐观更新UI
    const originalWork = { ...work };
    const updatedWork = {
      ...work,
      isLiked: !isCurrentlyLiked,
      likeCount: isCurrentlyLiked ? Math.max(0, work.likeCount - 1) : work.likeCount + 1
    };

    this.setData({
      work: updatedWork,
      isLikeLoading: true
    });

    // 发送请求到后端（与find页面使用相同的接口和参数）
    wx.request({
      url: 'http://localhost:8080/likes/likes/redisLike',
      method: 'POST',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        likerUid: userInfo.id,
        authorUid: work.authorId,
        targetId: work.id,
        targetType: 1
      },
      success: (res) => {
        console.log('点赞请求响应:', res.data);
        
        if (res.data.code === 200) {
          // 成功，使用后端返回的数据更新UI
          const result = res.data.data;
          const finalWork = {
            ...this.data.work,
            likeCount: result.likeCount || this.data.work.likeCount
          };
          
          this.setData({ work: finalWork });
          
          wx.showToast({
            title: result.message || (isCurrentlyLiked ? '取消点赞成功' : '点赞成功'),
            icon: 'success'
          });
        } else {
          // 失败，回滚UI
          this.setData({ work: originalWork });
          wx.showToast({
            title: res.data.msg || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('点赞请求失败:', err);
        // 网络错误，回滚UI
        this.setData({ work: originalWork });
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({ isLikeLoading: false });
      }
    });
  },

  // 评论点赞
  likeComment(e) {
    const commentId = e.currentTarget.dataset.id;
    const commentIndex = e.currentTarget.dataset.index;
    const { work } = this.data;
    
    // 检查是否正在加载中
    if (work.comments[commentIndex].isLikeLoading) {
      return;
    }
    
    // 获取用户信息
    let userInfo = {};
    try {
      userInfo = wx.getStorageSync('userInfo');
    } catch (e) {
      console.error('获取用户信息失败', e);
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    if (!userInfo.id) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 获取token
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    // 找到当前评论
    const comment = work.comments.find(c => c.id === commentId);
    if (!comment) {
      wx.showToast({
        title: '评论不存在',
        icon: 'none'
      });
      return;
    }

    // 设置加载状态
    const updatedComments = work.comments.map((c, index) => {
      if (index === commentIndex) {
        return {
          ...c,
          isLikeLoading: true
        };
      }
      return c;
    });

    this.setData({
      work: {
        ...work,
        comments: updatedComments
      }
    });

    // 乐观更新UI - 使用原始的work.comments数据
    const optimisticComments = work.comments.map((c, index) => {
      if (index === commentIndex) {
        return {
          ...c,
          isLiked: !c.isLiked,
          likeCount: c.isLiked ? c.likeCount - 1 : c.likeCount + 1,
          isLikeLoading: true
        };
      }
      return c;
    });

    this.setData({
      work: {
        ...work,
        comments: optimisticComments
      }
    });

    // 调用后端接口
    wx.request({
      url: 'http://localhost:8080/comments_likes/comments_likes/like',
      method: 'POST',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        commentId: commentId,
        userId: userInfo.id
      },
      success: (res) => {
        console.log('评论点赞响应：', res.data);
        if (res.data.code === 200) {
          const result = res.data.data;
          if (result.success) {
            // 成功，保持乐观更新的isLiked状态，只更新点赞数和清除加载状态
            const finalComments = this.data.work.comments.map((c, index) => {
              if (index === commentIndex) {
                return {
                  ...c,
                  likeCount: result.likeCount,
                  isLikeLoading: false
                  // 保持乐观更新时的isLiked状态
                };
              }
              return c;
            });

            this.setData({
              work: {
                ...work,
                comments: finalComments
              }
            });

            wx.showToast({
              title: result.action === 'like' ? '点赞成功' : '取消点赞',
              icon: 'success',
              duration: 1500
            });
          } else {
            // 失败，回滚UI状态
            this.rollbackCommentLikeStatus(commentIndex);
            wx.showToast({
              title: result.message || '操作失败',
              icon: 'none'
            });
          }
        } else {
          // 接口错误，回滚UI状态
          this.rollbackCommentLikeStatus(commentIndex);
          wx.showToast({
            title: res.data.msg || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('评论点赞请求失败', err);
        // 网络错误，回滚UI状态
        this.rollbackCommentLikeStatus(commentIndex);
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    });
  },

  // 回滚评论点赞状态
  rollbackCommentLikeStatus(commentIndex) {
    const { work } = this.data;
    const updatedComments = work.comments.map((c, index) => {
      if (index === commentIndex) {
        // 回滚到原始状态：切换isLiked，恢复likeCount，清除加载状态
        return {
          ...c,
          isLiked: !c.isLiked, // 切换回原始状态
          likeCount: c.isLiked ? c.likeCount - 1 : c.likeCount + 1, // 恢复原始点赞数
          isLikeLoading: false // 清除加载状态
        };
      }
      return c;
    });

    this.setData({
      work: {
        ...work,
        comments: updatedComments
      }
    });
  },

  // 获取评论点赞状态
  getCommentLikeStatus(commentIds, token) {
    let userInfo = {};
    try {
      userInfo = wx.getStorageSync('userInfo');
    } catch (e) {
      console.error('获取用户信息失败', e);
      return;
    }

    if (!userInfo.id || !commentIds || commentIds.length === 0) {
      return;
    }

    wx.request({
      url: `http://localhost:8080/comments_likes/comments_likes/like/status`,
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        commentIds: commentIds,
        userId: userInfo.id
      },
      success: (res) => {
        console.log('评论点赞状态响应：', res.data);
        if (res.data.code === 200) {
          const likeStatusMap = res.data.data;
          const { work } = this.data;
          
          // 更新评论的点赞状态
          const updatedComments = work.comments.map(comment => ({
            ...comment,
            isLiked: likeStatusMap[comment.id] || false,
            isLikeLoading: comment.isLikeLoading || false // 保留加载状态
          }));

          this.setData({
            work: {
              ...work,
              comments: updatedComments
            }
          });
        }
      },
      fail: (err) => {
        console.error('获取评论点赞状态失败', err);
      }
    });
  },

  // 获取评论点赞数
  getCommentLikeCounts(commentIds, token) {
    if (!commentIds || commentIds.length === 0) {
      return;
    }

    wx.request({
      url: `http://localhost:8080/comments_likes/comments_likes/like/counts`,
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        commentIds: commentIds
      },
      success: (res) => {
        console.log('评论点赞数响应：', res.data);
        if (res.data.code === 200) {
          const likeCountMap = res.data.data;
          const { work } = this.data;
          
          // 更新评论的点赞数
          const updatedComments = work.comments.map(comment => ({
            ...comment,
            likeCount: likeCountMap[comment.id] || 0,
            isLikeLoading: comment.isLikeLoading || false // 保留加载状态
          }));

          this.setData({
            work: {
              ...work,
              comments: updatedComments
            }
          });
        }
      },
      fail: (err) => {
        console.error('获取评论点赞数失败', err);
      }
    });
  },

  // 输入评论内容
  onInputChange(e) {
    this.setData({ commentContent: e.detail.value });
  },

  // 发送评论
  sendComment() {
    const { commentContent, work } = this.data;

    if (!commentContent.trim()) {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none'
      });
      return;
    }

    // 获取用户信息
    let userInfo = {};
    try {
      userInfo = wx.getStorageSync('userInfo');
    } catch (e) {
      console.error('获取用户信息失败', e);
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    if (!userInfo.id) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 获取token
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    // 显示加载提示
    wx.showLoading({
      title: '发送中...',
      mask: true
    });

    // 调用后端接口发送评论
    wx.request({
      url: 'http://localhost:8080/foodworks/comments',
      method: 'POST',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        userId: userInfo.id,
        targetType: 3,
        targetId: work.id,
        content: commentContent
      },
      success: (res) => {
        if (res.data.code === 200) {
          // 清空输入框
          this.setData({
            commentContent: ''
          });

          // 刷新评论列表，获取最新数据
          this.getComments(work.id, token, true);

          // 显示评论成功提示
          wx.showToast({
            title: '评论成功',
            icon: 'success',
            duration: 1500
          });
          
          // 延迟显示积分奖励提示
          setTimeout(() => {
            wx.showToast({
              title: '评论获得积分奖励！',
              icon: 'none',
              duration: 2000
            });
          }, 1500);
        } else {
          wx.showToast({
            title: res.data.msg || '评论失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('发送评论失败', err);
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 返回上一页
  navigateBack() {
    wx.navigateBack();
  },

  // 下拉刷新评论
  onPullDownRefresh() {
    console.log('触发评论下拉刷新');
    const { work } = this.data;
    if (work && work.id) {
      let token = '';
      try {
        token = wx.getStorageSync('token');
      } catch (e) {
        console.error('获取token失败', e);
      }
      this.getComments(work.id, token, true);
    }
    wx.stopPullDownRefresh();
  },

  // 上拉加载更多评论
  onReachBottom() {
    console.log('触发上拉加载更多评论');
    const { work, commentHasMore, commentIsLoading } = this.data;
    
    if (commentHasMore && !commentIsLoading && work && work.id) {
      let token = '';
      try {
        token = wx.getStorageSync('token');
      } catch (e) {
        console.error('获取token失败', e);
      }
      this.getComments(work.id, token, false);
    } else if (!commentHasMore) {
      wx.showToast({
        title: '没有更多评论了',
        icon: 'none'
      });
    }
  },

  // 清理HTML标签
  cleanHtmlTags(html) {
    if (!html) return '';
    // 移除HTML标签，保留文本内容
    return html.replace(/<[^>]*>/g, '');
  }
});